package com.antu.first.service.impl;

import com.antu.first.bean.Hotel;
import com.antu.first.bean.Swiper;
import com.antu.first.dao.SwiperDao;
import com.antu.first.dto.ImageHolder;
import com.antu.first.dto.SwiperOperationExecution;
import com.antu.first.enums.SwiperStateEnum;
import com.antu.first.exceptions.SwiperOperationException;
import com.antu.first.service.SwiperService;
import com.antu.first.util.ImageUtil;
import com.antu.first.util.PageBean;
import com.antu.first.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Administrator on 2018/3/6.
 */
@Service("swiperService")
public class SwiperServiceImpl implements SwiperService {
    @Autowired
    private SwiperDao swiperDao;
    Map<String, Object> map;
    List<Swiper>list;

    private void addSwiperImgList(List<Swiper> swiperList, List<ImageHolder> swiperImgList){
        String dest = null;
        if(swiperList != null && swiperList.get(0) != null && swiperList.get(0).getHotel() != null){
            dest = PathUtil.getHotelImgPath(swiperList.get(0).getHotel().gethId());
        }else{
            dest = PathUtil.getHotelImgPath(1011);
        }
        for(int i = 0; i < swiperList.size(); i++){
            String imgAddr = ImageUtil.generateNormalImg(swiperImgList.get(i), dest);
            Swiper swiper = swiperList.get(i);
            if(swiper != null){
                if(swiper.getHotel() != null){
                    swiper.setSwLoc(1);
                }else{
                    swiper.setSwLoc(0);
                }
                swiper.setSwAddr(imgAddr);
                swiper.setSwCreateTime(new Date());
                swiper.setSwStatus(0);
                if(swiper.getSwDesc() == null){
                    swiper.setSwDesc("swiper for hotel:"+swiper.getHotel().gethName());
                }
//              swiper.setSwSequence(99-i);
                if(swiper.getSwName() == null){
                    swiper.setSwName("轮播图"+i+swiper.getHotel().gethName()+new Random(10000));
                }
            }
        }
    }

    @Override
    public SwiperOperationExecution batchInsertSwiper(List<Swiper> swiperList, List<ImageHolder> swiperImgList) {
        if (swiperList != null && swiperList.size() >0 && swiperList.get(0) != null && swiperImgList.size() > 0) {
            try {
                //绑定图片地址和轮播图数据库信息
                addSwiperImgList(swiperList, swiperImgList);
                for(Swiper swiper : swiperList){
                    if (swiper.getSwAddr() == null || "".equals(swiper.getSwAddr())) {
                        return new SwiperOperationExecution(SwiperStateEnum.NULL_IMGADDR);
                    }
                }
                int effectNum = swiperDao.batchInsertSwiper(swiperList);
                if (effectNum <= 0) {
                    return new SwiperOperationExecution(SwiperStateEnum.CREATE_FAILED);
                } else {
                    return new SwiperOperationExecution(SwiperStateEnum.UPLOAD_SUCCESS);
                }
            } catch (Exception e) {
                throw new SwiperOperationException("SwiperServiceImpl-batchInsertSwiper，在创建轮播图列表的过程中发生错误："+e.getMessage());
            }
        } else {
            return new SwiperOperationExecution(SwiperStateEnum.EMPTY_LIST);
        }
    }

    @Override
    public Map<String, Object> updateSwiperById(Swiper swiper) {
        int i=swiperDao.updateSwiperById(swiper);
        map=new HashMap<String,Object>();
        if(i>0){
            map.put("success",true);
        }else {
            map.put("success",false);
            map.put("errMsg","更新失败，请检查数据是否完整");
        }
        return map;
    }

    @Override
    public Map<String, Object> allSwiperByHotelId(Swiper swiper,Integer currentPage,Integer pageSize) {
        map=new HashMap<String,Object>();
        int i=swiperDao.allSwiperByHotelIdCount(swiper);
        PageBean pageBean=new PageBean(currentPage,i,pageSize);//计算
        pageBean.setList(swiperDao.allSwiperByHotelId(swiper,pageBean));
        map.put("pageBean",pageBean);
        map.put("room",swiper);//传入的查询条件用于回显
        return map;
    }

    @Override
    public Map<String, Object> toPromoteSwiper(Integer swStatus) {
        list=new ArrayList<Swiper>();
        map=new HashMap<String,Object>();
        list=swiperDao.toPromoteSwiper(swStatus);
        map.put("swipers",list);
        return map;
    }



    @Override
    public Map<String, Object> deleteSwiperById(List<Swiper> swiperList) {
        map=new HashMap<String,Object>();
        list=new ArrayList<>();
        if(swiperList.size()>0){
            Hotel hotel=new Hotel();
            hotel.sethId(1);
            for (Swiper swiper:swiperList) {
                swiper.setHotel(hotel);//把操作的对应酒店从session中取出，设置到每个轮播图中（防止恶意操作）
            }
            list=swiperDao.batchSelectSwiperById(list);
            if (list.size()==swiperList.size()){
                int i=swiperDao.deleteSwiperById(list);//先删除数据库的数据
                if(i>0){
                    for (Swiper swiper:list) {
                        ImageUtil.deleteFileOrPath(swiper.getSwAddr());//数据库成功删除数据后，再删除服务器上的资源
                    }
                    map.put("success",true);
                }else {
                    map.put("success",false);
                    map.put("errMsg","删除失败，请刷新页面重试");
                }
            }else {
                map.put("success",false);
                map.put("errMsg","删除失败，请不要进行非法操作");
            }
        }else {
            map.put("success",false);
            map.put("errMsg","请至少选择一个轮播图");
        }
        return map;
    }

    private void addSwiperImg(Swiper swiper, ImageHolder swiperImg){
        String dest = null;
        if(swiper != null && swiper.getHotel() != null){
            dest = PathUtil.getHotelImgPath(swiper.getHotel().gethId());
        }else{
            dest = PathUtil.getHotelImgPath(1011);
        }
        String imgAddr = ImageUtil.generateNormalImg(swiperImg, dest);
        if(swiper.getHotel() != null){
            swiper.setSwLoc(1);
        }else{
            swiper.setSwLoc(0);
        }
        swiper.setSwAddr(imgAddr);
        swiper.setSwCreateTime(new Date());
        swiper.setSwStatus(0);
        if(swiper.getSwDesc() == null){
            swiper.setSwDesc("swiper for hotel:"+swiper.getHotel().gethName());
        }
//              swiper.setSwSequence(99-i);
        if(swiper.getSwName() == null){
            swiper.setSwName("轮播图"+swiper.getHotel().gethName()+new Random(10000));
        }
    }

    @Override
    public SwiperOperationExecution updateSwiper(Swiper swiper, ImageHolder swiperImg) {
        if(swiper != null && swiper.getHotel() != null && swiper.getHotel().gethId() != 0 ){
            try{
                //获取当前的Swiper的地址
                Swiper swiper1 = swiperDao.selectSwiperById(swiper.getSwId());
                if(swiper1 != null && swiper1.getSwAddr() != null){
                    ImageUtil.deleteFileOrPath(swiper1.getSwAddr());
                }
                addSwiperImg(swiper, swiperImg);
                if(swiper.getSwAddr() == null || "".equals(swiper.getSwAddr())){
                    return new SwiperOperationExecution(SwiperStateEnum.NULL_IMGADDR);
                }
                int effectNum = swiperDao.updateSwiper(swiper);
                if (effectNum <= 0) {
                    return new SwiperOperationExecution(SwiperStateEnum.CREATE_FAILED);
                } else {
                    return new SwiperOperationExecution(SwiperStateEnum.UPLOAD_SUCCESS);
                }
            }catch(Exception e){
                throw new SwiperOperationException("SwiperServiceImpl-batchInsertSwiper，在修改轮播图列表的过程中发生错误："+e.getMessage());
            }
        }else{
            return new SwiperOperationExecution(SwiperStateEnum.EMPTY_LIST);
        }
    }
    @Override
    public Map<String, Object> selectOneSwiperById(int swiperId) {
        map=new HashMap<String,Object>();
        map.put("swiper",swiperDao.selectSwiperById(swiperId));
        return map;
    }
}
